package com.example.android.BluetoothChat;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class BluetoothTextClient {
	private final BluetoothAdapter mAdapter;
	private final Handler mHandler;
	private ConnectThread mConnectThread;
	private int mState;
	// Constants that indicate the current connection state
	public static final int STATE_NONE = 0; // we're doing nothing
	public static final int STATE_CONNECT = 1; // now listening for incoming
	public static final String NAME_SECURE = "BluetoothChatSecure";
	public static final UUID MY_UUID_SECURE = UUID
			.fromString("0591e450-c99a-11e2-8b8b-0800200c9a66");
	private static final String TAG = "BluetoothClient";

	private Context context;

	public BluetoothTextClient(Context context, Handler handler) {
		mAdapter = BluetoothAdapter.getDefaultAdapter();
		mState = STATE_NONE;
		mHandler = handler;
		this.context = context;

	}

	public void config(String configInfo) {
		// TODO 配置蓝牙主机地址
	};

	public void connect(BluetoothDevice device) {
		// If the adapter is null, then Bluetooth is not supported
		if (mAdapter == null) {
			SendMessageToUI("Bluetooth is not be supported, please exit app");
			return;
		}
		if (!mAdapter.isEnabled()) {
			SendMessageToUI("Bluetooth is not isEnabled, please trun on and set Discoveryable");
			return;
		}
		mConnectThread = new ConnectThread(device);
		mConnectThread.start();
		mState = STATE_CONNECT;
	}

	private class ConnectThread extends Thread {
		private final BluetoothSocket mmSocket;
		private final BluetoothDevice mmDevice;
		private String mSocketType;

		public ConnectThread(BluetoothDevice device) {
			mmDevice = device;
			BluetoothSocket tmp = null;

			// Get a BluetoothSocket for a connection with the
			// given BluetoothDevice
			try {
				tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
				tmp.connect();
				SendMessageToUI("connect sucess:" + device.getName());
			} catch (IOException e) {
				e.printStackTrace();
				Log.e(TAG, "Socket Type: " + mSocketType + "create() failed");
				SendMessageToUI("connect fail:" + device.getName());
			}
			mmSocket = tmp;

		}

		public void run() {
			ClientConnectHandler mClientConnectHandler = new ClientConnectHandler(
					mmSocket, mmDevice.getName());
			mClientConnectHandler.start();
		}

		public void cancel() {
			Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this);
			try {
				mmSocket.close();
			} catch (IOException e) {
				Log.e(TAG, "Socket Type" + mSocketType
						+ "close() of server failed", e);
			}
		}
	}

	private class ClientConnectHandler extends Thread {
		private final BluetoothSocket mmSocket;
		private final InputStream mmInStream;
		private final OutputStream mmOutStream;
		private boolean state = true;
		private String name;

		public ClientConnectHandler(BluetoothSocket socket, String name) {
			Log.d(TAG, "create ClientConnectHandler: " + name);
			mmSocket = socket;
			InputStream tmpIn = null;
			OutputStream tmpOut = null;
			this.name = name;
			// Get the BluetoothSocket input and output streams
			try {
				tmpIn = socket.getInputStream();
				tmpOut = socket.getOutputStream();
			} catch (IOException e) {
				e.printStackTrace();
				Log.e(TAG, "temp sockets not created", e);
			}

			mmInStream = tmpIn;
			mmOutStream = tmpOut;
		}

		public void run() {
			Log.i(TAG, "connecting");
			byte[] buffer = new byte[1024];
			int bytes;

			// Keep listening to the InputStream while connected
			while (state) {
				try {
					// Read from the InputStream
					bytes = mmInStream.read(buffer);

					// Send the obtained bytes to the UI Activity
					// mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes,
					// -1, buffer).sendToTarget();
					handlerData(buffer, bytes);
				} catch (IOException e) {
					Log.e(TAG, "disconnected", e);
					break;
				}
			}
		}

		/**
		 * Write to the connected OutStream.
		 * 
		 * @param buffer
		 *            The bytes to write
		 */
		public void write(byte[] buffer) {
			try {
				mmOutStream.write(buffer);
				// Share the sent message back to the UI Activity
				// mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1,
				// buffer)
				// .sendToTarget();
			} catch (IOException e) {
				Log.e(TAG, "Exception during write", e);
			}
		}

		public void cancel() {
			try {
				state = false;
				mmSocket.close();
				SendMessageToUI("cancel connect to" + name);
			} catch (IOException e) {
				Log.e(TAG, "close() of connect socket failed", e);

			}
		}
	}

	public void SendMessageToUI(String string) {
		Message msg = new Message();
		msg.what = 0;
		msg.obj = string;
		mHandler.sendMessage(msg);
		// Message msg =
		// mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
		// Bundle bundle = new Bundle();
		// bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
		// msg.setData(bundle);
		// mHandler.sendMessage(msg);
	}

	public void handlerData(byte[] buffer, int bytes) {
		SendMessageToUI("receive a message :" + new String(buffer, 0, bytes));
	}

	public void stop() {
		if (null != mConnectThread) {
			mState = STATE_NONE;
			mConnectThread.cancel();
		}
		// TODO 停止所有的客户端连接
	}
}
